package cn.edu.tju.elm.service;

import cn.edu.tju.elm.exception.ImageIOException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Service
public class ImageService {

    @Value("${image.upload-dir}")
    private final String uploadDir;

    public ImageService(@Value("${image.upload-dir}")String uploadDir) {
        this.uploadDir = uploadDir;
    }

    public String saveImage(MultipartFile file) {
        // 生成唯一文件名（防止重名）
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename = UUID.randomUUID() + extension;

        // 构建目标文件路径
        File targetFile = new File(uploadDir + "/" + newFilename).getAbsoluteFile();

        // 保存文件
        try {
            file.transferTo(targetFile);
        } catch (IOException e) {
            log.error(targetFile.toString());
            throw new ImageIOException("图片保存失败，请稍后再试");
        }

        // 4. 动态拼接完整绝对URL（关键！）
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String scheme = request.getScheme();          // 协议（http/https）
        String serverName = request.getServerName();  // 服务器IP或域名
        int serverPort = request.getServerPort();     // 服务器端口
        String contextPath = request.getContextPath();// 应用上下文路径（如"/myapp"）

        String fullImageUrl = String.format("%s://%s:%d%s/uploads/%s",
                scheme, serverName, serverPort, contextPath, newFilename);

        // 返回访问 URL（根据静态资源映射）
        return fullImageUrl;
    }
}
